import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:znmm/UI/utils/my_global.dart';
import 'package:znmm/UI/utils/sharedpre_utils.dart';
import 'package:znmm/config/app_init.dart';
import 'package:znmm/config/app_routes.dart';
import 'package:znmm/network/api_url.dart';
import 'package:znmm/network/dio_https.dart';
import 'package:znmm/network/notify_listener.dart';

import 'user_info_manage.dart';

class LoginMag {
  static final LoginMag _singleton = LoginMag._internal();
  factory LoginMag() {
    return _singleton;
  }

  LoginMag._internal();

  void doSomething() {
    print("Doing something...");
  }

  //登录
  void reqLogin(String username, String password, bool remember,
      {void Function()? callback}) {
    // if (username.isEmpty && password.isEmpty) {
    //   //跳到首页
    //   Get.offNamedUntil(RouteNames.homeRoute, (route) => false);
    //   return;
    // }

    if (username.isEmpty) {
      MyGlobal.showInfo("Please enter user name");
      return;
    }

    if (password.isEmpty) {
      MyGlobal.showInfo("Please enter password");
      return;
    }

    String basicAuth =
        'Basic ${base64Encode(utf8.encode('$username:$password'))}';

    DioHttps dioUtil = DioHttps.instance!;
    //dioUtil.openLog();
    dioUtil
        .request<dynamic>(
      APIUrl.strLogin,
      method: DioMethod.post,
      //bIsShowResponse: true,
      options1: Options(headers: {
        "Authorization": basicAuth,
      }),
    )
        .then((response) {
      // 处理响应数据

      print("response:$response");
      if (response == null) return;
      //
      UserInfoMag().fromJson(response, username, password);

      SharedPrefUtil().setData(SharedKey.strRemember, remember);
      if (remember) {
        SharedPrefUtil().setData(SharedKey.strLoginUserNameKey, username);
        SharedPrefUtil().setData(SharedKey.strLoginPwdKey, password);
      } else {
        SharedPrefUtil().removeData(SharedKey.strLoginUserNameKey);
        SharedPrefUtil().removeData(SharedKey.strLoginPwdKey);
      }

      //跳到首页
      Get.offNamedUntil(RouteNames.homeRoute, (route) => false);
    });
  }

  //注册
  void reqRegister(
      String username, String email, String password1, String password2,
      {void Function(dynamic)? callback}) {
    if (username.isEmpty) {
      MyGlobal.showInfo("please enter user name");
      return;
    }

    if (email.isEmpty || !MyGlobal.isValidEmail(email)) {
      MyGlobal.showInfo("Please enter a valid email address");
      return;
    }

    if (password1.isEmpty || password2.isEmpty) {
      MyGlobal.showInfo("Please enter password");
      return;
    }

    if (password1 != password2) {
      MyGlobal.showInfo("Passwords are inconsistent");
      return;
    }

    // if (callback != null) {
    //   callback("callback");
    // }

    String urlStr =
        "${APIUrl.strRegister}consumer_key=$consumer_key&consumer_secret=$consumer_secret";

    print("urlStr = $urlStr");
    DioHttps dioUtil = DioHttps.instance!;
    //dioUtil.openLog();
    dioUtil.request<dynamic>(
      urlStr,
      method: DioMethod.post,
      //bIsShowResponse: true,
      bIsShowRequest: true,
      data: {
        "username": username,
        "email": email,
        "password": password1,
        //"confirmPassword": password2,
      },
      //baseUrlIndex: 1,
    ).then((response) {
      // 处理响应数据

      print("response:$response");
      if (response == null) return;

      String emailStr = response["email"];
      if (email == emailStr) {
        //MyGlobal.showInfo("registration success!");

        print("username:$username");
        print("password1:$password1");

        SharedPrefUtil().setData(SharedKey.strLoginUserNameKey, username);
        SharedPrefUtil().setData(SharedKey.strLoginPwdKey, password1);

        NotifyCenter().postNotification(NotifyKey.registerKey);

        if (callback != null) {
          callback("callback");
        }
      }
    }).catchError((error) {
      // 处理错误
    });
  }

  //删除账号
  void reqDeleteCustomers({void Function()? callback}) {
    String strId = UserInfoMag().user_id;
    String urlStr =
        "/wp-json/wc/v3/customers/$strId?consumer_key=$consumer_key&consumer_secret=$consumer_secret";
    DioHttps dioUtil = DioHttps.instance!;
    dioUtil.request<dynamic>(
      urlStr,
      method: DioMethod.delete,
      //bIsShowResponse: true,
      data: {
        "force": true,
      },
    ).then((response) {
      // 处理响应数据

      print("response:$response");
      if (response == null) return;

      AppInit.logoutDispose();
    });
  }
}
